package com.example.movie.mate.interceptor;

import cn.hutool.json.JSONUtil;
import com.example.movie.mate.pojo.core.Principle;
import com.example.movie.mate.web.JsonResult;
import com.example.movie.mate.web.StateCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果此方法返回true，则继续执行后续的拦截器，直到所有拦截器都执行完，再执行处理请求的方法
        // 如果此方法返回false，则不再执行后续的拦截器（也包含处理请求的方法），直接返回响应结果给客户端

        // 拦截路径
        log.debug("拦截路径：{}", request.getRequestURI());
        // 判断Session是否存在登录信息
        HttpSession session = request.getSession();
        if (session.getAttribute(Principle.SESSION_KEY) == null) {
            String message = "无登录信息，可能已过期，请登录！";
            JsonResult jsonResult = JsonResult.fail(StateCode.ERROR_UNAUTHORIZED, message);

            response.setCharacterEncoding("UTF-8");
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            PrintWriter writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(jsonResult));
            writer.close();
            return false;
        }
        return true;
    }

}
